package applet.misc.component;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

public class JIntTextField extends JTextField
{
	private static final long serialVersionUID = 7255065862506055479L;

	public JIntTextField(int defval) { super("" + defval); }

	protected Document createDefaultModel() { return new IntTextDocument(); }

	public boolean isValid()
	{
		try
		{
			Integer.parseInt(getText());
			return true;
		}
		catch (Exception e) { return false; }
	}

	public int getValue()
	{
		try
		{
			return Integer.parseInt(getText());
		}
		catch (Exception e) { return 0; }
	}

	private class IntTextDocument extends PlainDocument 
	{
		private static final long serialVersionUID = 5184020844225862931L;

		public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
		{
			if (str == null)
				return;
			String oldString = getText(0, getLength());
			String newString = oldString.substring(0, offs) + str + oldString.substring(offs);
			try
			{
				Integer.parseInt(newString + "0");
				super.insertString(offs, str, a);
			}
			catch (NumberFormatException e) { }
		}
	}
}